const express = require('express');
const router = express.Router();
const Response = require('../utils/Response');

// 引入mysql连接池
const pool = require('../utils/db');

// 查询所有用户信息
router.post('/user', async (req, res) => {
  try {
    let size = parseInt(req.body.pagesize);
    let start = (req.body.page - 1) * size;

    let sql1 = 'select * from user where ID != 1 limit ?,?';
    let sql2 = 'select count(*) as count from user where ID != 1';
    let result = await pool.querySync(sql1, [start, size]);
    let result2 = await pool.querySync(sql2);
    let total = result2[0].count;
    res.send(
      Response.ok({
        page: parseInt(req.body.page),
        pagesize: size,
        total,
        result,
      })
    );
  } catch (error) {
    res.send(Response.error(error));
  }
});

//添加用户
router.post('/userAdd', (req, res) => {
  try {
    let sql = 'INSERT INTO user VALUES(null,?,?,?,?);';
    let { username, password, role, addtime } = req.body;

    let result = pool.query(sql, [username, password, role, addtime]);
    res.send(Response.ok());
  } catch (error) {
    res.send(Response.error(error));
  }
});

//删除用户
router.post('/userDel', (req, res) => {
  try {
    let sql = 'delete from user where id=?';
    pool.query(sql, [req.body.id]);
    res.send(Response.ok());
  } catch (error) {
    res.send(Response.error(error));
  }
});

//修改用户信息
router.post('/userUpdate', (req, res) => {
  try {
    let sql = 'update user set username=?,password=?,role=? where id=?';
    let { username, password, role, id } = req.body;
    pool.query(sql, [username, password, role, id]);
    res.send(Response.ok());
  } catch (error) {
    res.send(Response.error(error));
  }
});

//通过用户名模糊查询
router.post('/userLike/name', (req, res) => {
  try {
    let sql = 'select * from user where username like ? and id != 1';
    pool.query(sql, [`%${req.body.name}%`], (err, result) => {
      res.send(Response.ok(result));
    });
  } catch (error) {
    res.send(Response.error(error));
  }
});
// 将router对象导出
module.exports = router;
